define(['../common/service'],function(http){
    function Data(){
        var self = this;
        this.sessionData = window.sessionStorage;

        //广告创意里面的  选择列表框
        //行动号召
        this.callToActions = {
            "outlink" :  [
                {text:I18N.getText('createAd', 'download'),value:"DOWNLOAD",id:5},
                {text:I18N.getText('createAd', 'shopNow'),value:"SHOP_NOW",id:1},
                {text:I18N.getText('createAd', 'bookNow'),value:"BOOK_TRAVEL",id:2},
                {text:I18N.getText('createAd', 'learnMore'),value:"LEARN_MORE",id:3},
                {text:I18N.getText('createAd', 'signUp'),value:"SIGN_UP",id:4},
                {text:I18N.getText('createAd', 'watchMore'),value:"WATCH_MORE",id:6},
                {text:I18N.getText('createAd', 'applyNow'),value:"APPLY_NOW",id:7},
                {text:I18N.getText('createAd', 'contactUs'),value:"CONTACT_US",id:8}
            ],
            "app" :[
                {text:I18N.getText('createAd', 'installNow'),value:"INSTALL_MOBILE_APP",id:7},
                {text:I18N.getText('createAd', 'shopNow'),value:"SHOP_NOW",id:1},
                {text:I18N.getText('createAd', 'bookNow'),value:"BOOK_TRAVEL",id:2},
                {text:I18N.getText('createAd', 'listenNow'),value:"LISTEN_MUSIC",id:3},
                {text:I18N.getText('createAd', 'learnMore'),value:"LEARN_MORE",id:4},
                {text:I18N.getText('createAd', 'signUp'),value:"SIGN_UP",id:5},
                {text:I18N.getText('createAd', 'download'),value:"DOWNLOAD",id:6},
                {text:I18N.getText('createAd', 'watchVideo'),value:"WATCH_VIDEO",id:8},
                {text:I18N.getText('createAd', 'watchMore'),value:"WATCH_MORE",id:9},
                {text:I18N.getText('createAd', 'useApp'),value:"USE_APP",id:10},
                {text:I18N.getText('createAd', 'playGame'),value:"PLAY_GAME",id:11}
            ]
        };

       this.global = [{
        "location":[{
            "name": I18N.getText('createAd', 'europe'),
            "key": "Europe",
            "region":[
                {"name":"United Kingdom", "countryCode":"GB"},
                {"name":"Turkey", "countryCode":"TR"},
                {"name":"France", "countryCode":"FR"},
                {"name":"Italy", "countryCode":"IT"},
                {"name":"Spain", "countryCode":"ES"},
                {"name":"Germany", "countryCode":"DE"},
                {"name":"Sweden", "countryCode":"SE"},
                {"name":"Belgium", "countryCode":"BE"},
                {"name":"Poland", "countryCode":"PL"},
                {"name":"Greece", "countryCode":"GR"},
                {"name":"Czech Republic", "countryCode":"CZ"},
                {"name":"Netherlands", "countryCode":"NL"},
                {"name":"Portugal", "countryCode":"PT"},
                {"name":"Denmark", "countryCode":"DK"},
                {"name":"Norway", "countryCode":"NO"},
                {"name":"Switzerland", "countryCode":"CH"},
                {"name":"Austria", "countryCode":"AT"},
                {"name":"Finland", "countryCode":"FI"},
                {"name":"Ireland", "countryCode":"IE"},
                {"name":"Hungary", "countryCode":"HU"},
                {"name":"Bulgaria", "countryCode":"BG"},
                {"name":"Romania", "countryCode":"RO"},
                {"name":"Slovakia", "countryCode":"SK"},
                {"name":"Russia", "countryCode":"RU"},
                {"name":"Croatia", "countryCode":"HR"}
            ]},
            {
            "name": I18N.getText('createAd', 'northAmerica'),
            "key": "NorthAmerica",
            "region":[
                {"name":"United States", "countryCode":"US"},
                {"name":"Canada", "countryCode":"CA"},
                {"name":"Mexico", "countryCode":"MX"},
                {"name":"Puerto Rico", "countryCode":"PR"},
                {"name":"Dominican Republic", "countryCode":"DO"},
                {"name":"Costa Rica", "countryCode":"CR"},
                {"name":"Guatemala", "countryCode":"GT"},
                {"name":"Panama", "countryCode":"PA"},
                {"name":"El Salvador", "countryCode":"SV"}
            ]},
            {
            "name": I18N.getText('createAd', 'southAmerica'),
            "key": "SouthAmerica",
            "region":[
                {"name":"Argentina", "countryCode":"AR"},
                {"name":"Colombia", "countryCode":"CO"},
                {"name":"Chile", "countryCode":"CL"},
                {"name":"Venezuela", "countryCode":"VE"},
                {"name":"Brazil", "countryCode":"BR"},
                {"name":"Peru", "countryCode":"PE"},
                {"name":"Ecuador", "countryCode":"EC"},
                {"name":"Uruguay", "countryCode":"UY"},
                {"name":"Bolivia", "countryCode":"BO"}
            ]},
            {
            "name": I18N.getText('createAd', 'asia'),
            "key": "Asian",
            "region":[
                {"name":"Indonesia", "countryCode":"ID"},
                {"name":"Philippines", "countryCode":"PH"},
                {"name":"India", "countryCode":"IN"},
                {"name":"Malaysia", "countryCode":"MY"},
                {"name":"Thailand", "countryCode":"TH"},
                {"name":"Israel", "countryCode":"IL"},
                {"name":"Saudi Arabia", "countryCode":"SA"},
                {"name":"Singapore", "countryCode":"SG"},
                {"name":"Pakistan", "countryCode":"PK"},
                {"name":"U.A.E", "countryCode":"AE"},
                {"name":"South Korea", "countryCode":"KR"},
                {"name":"Japan", "countryCode":"JP"},
                {"name":"Vietnam", "countryCode":"VN"},
                {"name":"Lebanon", "countryCode":"LB"},
                {"name":"Jordan", "countryCode":"JO"},
                {"name":"Bangladesh", "countryCode":"BD"},
                {"name":"Sri Lanka", "countryCode":"LK"}
            ]},
            {
            "name": I18N.getText('createAd', 'africa'),
            "key": "Africa",
            "region":[
                {"name":"Egypt", "countryCode":"EG"},
                {"name":"South Africa", "countryCode":"ZA"},
                {"name":"Morocco", "countryCode":"MA"},
                {"name":"Nigeria", "countryCode":"NG"},
                {"name":"Tunisia", "countryCode":"TN"},
                {"name":"Algeria", "countryCode":"DZ"},
                {"name":"Kenya", "countryCode":"KE"},
                {"name":"Ghana", "countryCode":"GH"}
            ]},
            {
            "name": I18N.getText('createAd', 'oceania'),
            "key": "Oceania",
            "region":[
                {"name":"Australia", "countryCode":"AU"},
                {"name":"New Zealand", "countryCode":"NZ"}
            ]
        }],
        "lang":[
            {
            "name": I18N.getText('createAd', 'arabic'),
            "key": "Arabic",
            "region":[
                    {"name":"Saudi Arabia", "countryCode":"SA"},
                    {"name":"U.A.E", "countryCode":"AE"},
                    {"name":"Lebanon", "countryCode":"LB"},
                    {"name":"Jordan", "countryCode":"JO"},
                    {"name":"Egypt", "countryCode":"EG"},
                    {"name":"Algeria", "countryCode":"DZ"},
                    {"name":"Morocco", "countryCode":"MA"}
            ]
            },
            {
            "name": I18N.getText('createAd', 'portuguese'),
            "key": "Portuguese",
            "region":[
                    {"name":"Portugal", "countryCode":"PT"},
                    {"name":"Brazil", "countryCode":"BR"},
                    {"name":"Spain", "countryCode":"ES"}
            ]},
            {
            "name": I18N.getText('createAd', 'spanish'),
            "key": "spanish",
            "region":[
                {"name":"Spain", "countryCode":"ES"},
                {"name":"Argentina", "countryCode":"AR"},
                {"name":"Bolivia", "countryCode":"BO"},
                {"name":"Chile", "countryCode":"CL"},
                {"name":"Colombia", "countryCode":"CO"},
                {"name":"Costa Rica", "countryCode":"CR"},
                {"name":"Dominican Republic", "countryCode":"DO"},
                {"name":"Ecuador", "countryCode":"EC"},
                {"name":"El Salvador", "countryCode":"SV"},
                {"name":"Guatemala", "countryCode":"GT"},
                {"name":"Mexico", "countryCode":"MX"},
                {"name":"Panama", "countryCode":"PA"},
                {"name":"Peru", "countryCode":"PE"},
                {"name":"Uruguay", "countryCode":"UY"},
                {"name":"Venezuela", "countryCode":"VE"},
                {"name":"United States", "countryCode":"US"},
                {"name":"Canada", "countryCode":"CA"},
                {"name":"Morocco", "countryCode":"MA"},
                {"name":"Netherlands", "countryCode":"NL"},
                {"name":"Philippines", "countryCode":"PH"}
            ]},
            {
            "name": I18N.getText('createAd', 'french'),
            "key": "French",
            "region":[
                {"name":"France", "countryCode":"FR"},
                {"name":"Canada", "countryCode":"CA"},
                {"name":"Belgium", "countryCode":"BE"},
                {"name":"Sweden", "countryCode":"SE"},
                {"name":"Algeria", "countryCode":"DZ"},
                {"name":"Lebanon", "countryCode":"LB"},
                {"name":"Morocco", "countryCode":"MA"}
            ]},
            {
            "name": I18N.getText('createAd', 'italian'),
            "key": "Italian",
            "region":[
                {"name":"Italy", "countryCode":"IT"},
                {"name":"Germany", "countryCode":"DE"},
                {"name":"France", "countryCode":"FR"},
                {"name":"Switzerland", "countryCode":"CH"}
            ]
        	}
          ]
}];

        if(this.sessionData && this.sessionData.apps){
            this.apps = JSON.parse(this.sessionData.apps);
            this.app = JSON.parse(this.sessionData.app);
            this.prods = JSON.parse(this.sessionData.prods);
            //如果没有选择平台，刷新页面
            if(this.sessionData.prod){
                this.prod = JSON.parse(this.sessionData.prod);
            } else {
                this.prod = -1;
            }

        }else{
           this.apps = [];//应用数组
           this.app = {};//选中的应用
           this.prods = [];//应用下面的产品配置数组
           this.prod = {};//选中的产品名
           this.aca = [];
           this.langs = [];
           this.radio = 0;
        }
        this.nowTemp =[];
        if(this.sessionData.userTemp){//有模板数据，没有按照默认数据来
            this.userTemp = JSON.parse(this.sessionData.userTemp);
            this.temp = JSON.parse(this.sessionData.temp);
            this.nowTemp = JSON.parse(this.sessionData.temp);
            this.tempIndex = JSON.parse(this.sessionData.tempIndex);
            //可供选择的自定义受众列表
            this.aca = JSON.parse(this.sessionData.aca);

            //刷新存在问题
            if(this.cache){
                this.adWords = this.cache.adWords;//广告词
                this.adCampSeq = this.cache.adCampSeq;
                this.adSetSeq = this.cache.adSetSeq,
                this.adGroupSeq = this.cache.adGroupSeq

                this.cache = JSON.parse(this.sessionData.cache);
                this.langs = JSON.parse(this.sessionData.langs);
            }else{
				this.pageList = [[]];
				this.adWords = [""];
				this.adTitle = "";
				this.page = null;
				this.adCampSeq = [];
				this.adSetSeq = [];
				this.adGroupSeq = []
			}

        }else{
            this.temp = null;
            this.userTemp = null;
           //this.pageList = [[]];
            this.tempIndex = -1;
            this.adWords = [""];
            this.adTitle = "";
            //this.page = null;
            this.adCampSeq = [];
            this.adSetSeq = [];
            this.adGroupSeq = []
        }

		if(this.sessionData && this.sessionData.entrustAccounts){
            this.entrustAccounts = JSON.parse(this.sessionData.entrustAccounts);
            this.tagNames = JSON.parse(this.sessionData.tagNames);
            this.adTitleList = JSON.parse(this.sessionData.adTitleList);
            this.pageList = JSON.parse(this.sessionData.pageList);
            this.adTitle = JSON.parse(this.sessionData.adTitle);
            this.page = JSON.parse(this.sessionData.page);
		}

        this.prices = {};//[cpc:[{}],cpm:[],ocpm:[],cpa:[]]
        //性别
        if (this.sessionData.Gender){
            this.Gender = JSON.parse(this.sessionData.Gender);
        } else {
            this.Gender = {
                'GenderRenders' : {
                    0 : {
                        val: 0,
                        name: I18N.getText('createAd', 'all'),
                        checked : true
                    },
                    1 : {
                        val: 1,
                        name: I18N.getText('createAd', 'men')
                    },
                    2 : {
                        val: 2,
                        name: I18N.getText('createAd', 'women')
                    }
                },
                'DefaultGender' : 0,
                'GenderCount' : 3
            }
        }

        this.assetIMGSource = null;//图片的原始数据
        this.assetVIDSource = null;//视频的原始数据
        this.adImages=[];//图片
        this.adVideos=[];//视频
        this.adImagesGroup = [];//轮播图片
        //[{cpc:[{}],cpm:[],ocpm:[],cpa:[]},{cpc:[{}],cpm:[],ocpm:[],cpa:[]}]
        this.imgRefine = function(id,tag,index){
            var arr = self.assetIMGSource;
            if(tag == "del"){
                self.adImages.splice(index,1);
            }else{
                if(arr){
                    for(var i=0;i<arr.length;i++){
                        var o = arr[i];
                        if(o.id==id){
                               o.count = 1;
                               self.adImages.push(o);
                            break;
                        }
                    }
                }
            }
        }
        this.imgsRefine = function(id,tag,index){
            var arr = self.assetIMGSource;
            if(tag=="del"){
                self.adImagesGroup.splice(index,1);
            }else{
                if(arr){
                    for(var i=0;i<arr.length;i++){
                        var o = arr[i];
                        if(o.id==id){
                               o.count = 1;
                               self.adImagesGroup[index].push(o);
                            break;
                        }
                    }
                }
            }
        }

        /**
         * 删除图片
         * @id 图片id
         */
        this.deleteAdimage = function(id){
            if(id==undefined){
                return;
            }
            var idx = -1;
            $.each(self.adImages,function (i,v) {
                if(v.id==id){
                   idx = i;
                   return false;
                }
            })
            if(idx>=0){
               self.adImages.splice(idx,1);
            }
        }

        /**
         * 删除轮播图图片
         * @id 图片id
         * @index 图片在图片组中的 index
         * @adImgGroupIdx 图片组的 index
         */
        this.deleteCarouselAdimage = function(id,index,adImgGroupIdx){
            if(id==undefined){
                return;
            }
            self.adImagesGroup[adImgGroupIdx].splice(index,1);
        }

        this.videoRefine = function(md5){
            console.log(md5)
            var arr = self.assetVIDSource;
            self.adVideos = [];
            if(arr){
                for(var i=0;i<arr.length;i++){
                    var the = arr[i];
                    if(the.md5 == md5) {
                        self.adVideos.push({mongoId : the.mongodbId, md5: the.md5, name:the.name,visitPath:the.visitPath});
                        break;
                    }
                }
            }
        }

        /***
        **设置单价
        **/
        this.setSPrice = function(gindex,mode,index,val,tag){
            switch(mode){
                case "CPC":
                    var o = {"CLICKS":val};
                    break;
                case "CPM":
                    o = {"IMPRESSIONS":val};
                    break;
                case "CPA":
                    o = {"ACTIONS":val};
                    break;
                case "OCPM":
                    o = {};
                    o[tag||"ACTIONS"] = val;
                    break;
            }
            self.prices[gindex][mode].univalents[index] = JSON.stringify(o);
        }
        /**
        **删除用户定位相关的本地缓存 ,,更换用户定位模板
        **/
        this.delTemp = function(){
            self.deleteUserAudienceResults();
            delete window.existsPreviewUserAudience;
        };
        //更换应用 更换平台
        this.delUserTemp = function(){
//            self.templateTargetingSpecs=JSON.stringify({});
            delete window.existsPreviewUserAudience; //用户定位是否生成
            self.deleteUserAudienceResults();
            self.sessionData.removeItem("userTemp");
            self.sessionData.removeItem("temp");
            self.temp = null;
            self.userTemp = null;
            //存选中的模板
            self.tempIndex =-1;
            self.sessionData.tempIndex = -1;
        }
        this.delGroupsIds = [];//删除的用户过滤组
        this.locstr = function(o){//选中的地区国家的字符串
            var str='',locArray = [];
            if(o.countries&&o.countries.length>0){
                locArray = locArray.concat(o.countries);
            }

            if(o.cities&&o.cities.length>0){
                locArray = locArray.concat(o.cities);
            }
            locArray.forEach(function(item){
                str +=(str!=''?", ":'')+item.name;
            })
            return str;
        };
        this.adTags = [];//搜索广告语的关键词
        this.priceType = 0;// 默认0 单地区，1 多地区
        this.renew = function(){
            self = {};
        }

        this.schedule = {};
        this.importTempIds = [];
        this.importTemp = [];

        this.settleData = [];//生成的用户定位列表
        this.removeData = [];//删除的用户定位信息
        //用户定位原始数据--不重新生成用户定位或者修改条件之前不能删除
        this.saveUserAudienceResults = function(result){
            this.sessionData.userAudienceResults = JSON.stringify(result);
        }
        this.getUserAudienceResults = function(result){
            if(this.sessionData.userAudienceResults){
                return JSON.parse(this.sessionData.userAudienceResults);
            } else {
                return {};
            }
        }
        this.deleteUserAudienceResults = function(){
            console.log("删除模板")
            this.sessionData.userAudienceResults = JSON.stringify({});
        }

        this.pageCols = 12;//每页显示的条数
        this.currentPage = 1;//当前第一页
        //选择的素材类型
//        this.chooseType = function(){
//            return $("div.nav-pills>label:has(input[type=radio]:checked)").data("target").replace("#",'');
//        }
        this.chooseType = "img";
        //加入内存区数据
        this.addItem = function(id,val){
            switch(id){
                case "WirelessConnection":
                    var val = [parseInt(val)||0];//[0]
                    break;
                case "PageTypes":
                    //val = [0];//[0]
                    break;
                case "CustomAudience":
                    val = {};
                    break;
                case "Location":
                     val = {};
                    break;
                case "Age":
                    val = self.cache.adPublishConditionDetailCache.age;
                    break;
                case "Gender":
                    val = [parseInt(val)];
                    break;
                case "Interests":
                    val = [];//{id:"",name:"",locale:"en_US"}
                    break;
                case "Connections":
                case "CollegeYears":
                case "Behavior":
                case "NewInterestedIn":
                case "NewRelationshipStatus":
                case "Languages":
                case "EducationStatuses":
                case "EducationMajors":
                case "EducationSchools":
                case "WorkEmployers":
                case "WorkPositions":
                case "Industries":
                case "EthnicAffinity":
                case "Generation":
                case "FamilyStatuses":
                case "Politics":
                case "LifeEvents":
                    val = null;
                    break;
                case "ad-txt":
                    self.adWords.push("");
                    self.cache.adWords = self.adWords;
                    self.sessionData.cache = JSON.stringify(self.cache);
                    return "";
                    break;
                case "price-config-field":
                    //var dat = self.prices[parseInt(arguments[1])][parseInt(arguments[2])];
                    //self.setSPrice(parseInt(arguments[1]),arguments[2],0,0);
                    //return dat;
                    return self.getBidInfoVo(arguments[1],arguments[2]);

            }
            if(val) {
                self.nowTemp[id].push(val);
            }
            return val;
        }

        //删除临时区的某个指定数据
        this.delItem = function(id,index){
            switch(id) {
                case "ad-txt":
                    self.adWords.splice(index,1);//修改adWords 数据
                    self.cache.adWords = self.adWords;
                    self.sessionData.cache = JSON.stringify(self.cache);
                    break;
                case "price-config-field":
                    self.prices[index].splice(arguments[2],1);
                    break;
                case "Location":
                    self.nowTemp[id].splice(index,1);
                    break;
                case "Languages": //语言
                case "NewInterestedIn": //感情状况-性取向
                case "EthnicAffinity":
                case "NewRelationshipStatus": //感情状况-感情状况
                case "EducationStatuses": //学历-教育程度
                case "EducationMajors": //学历-研究领域
                case "EducationSchools": //学历-学校
                case "WorkEmployers": //工作-雇主
                case "WorkPositions": //工作-职务
                case "Industries": //工作-行业
                case "Behavior": //行为
                case "FamilyStatuses": //父母(统统包括)
                case "Politics":  //政治(美国)
                case "LifeEvents":  //生活纪事
                case "Generation": //世代
                    if(index == undefined){ //删除整个条件
                        self.nowTemp[id]=[[]];
                    } else {
                        self.nowTemp[id][0].splice(index,1);
                    }
                    break;
                case "CollegeYears": //学历-大学就读年份
                    self.nowTemp[id] = [{}];
                    break;
                case "Connections": //联系单独处理
                      self.nowTemp[id] = [{type:0,connections:[{id:self.app.fbConnectionObjectId, name:self.app.name}]}];//删除整个条件
                    break;
                case "sim-audience": //刪除相似受眾
                    //self.nowTemp[id] = [{type:0,connections:[{id:self.app.fbConnectionObjectId, name:self.app.name}]}];//删除整个条件
                    break;
                default :
                    self.nowTemp[id].splice(index, 1);
            }
        }

        this.update = function(id,index,val){
            switch(id){
                case "PageTypes":
                  /*  if(val == 0){
                        self.nowTemp[id][index]= [0];
                    } else {
                        self.nowTemp[id][index]= [0,1];
                    }*/
                    self.nowTemp[id][index]=val;
                    break;
                case "WirelessConnection":
                case "Gender":
                    self.nowTemp[id][index]=[parseInt(val)];
                    break;
                case "CustomAudience":
                case "Location":
                case "Age":
                case "Interests":
                    self.nowTemp[id][index]=val;
                    break;
                case "Languages":
                case "NewInterestedIn":
                case "NewRelationshipStatus":
                case "WorkEmployers":
                case "WorkPositions":
                case "LifeEvents":
                case "Politics":
                case "FamilyStatuses":
                case "Generation":
                case "Industries":
                case "EthnicAffinity":
                case "EducationStatuses":
                case "EducationSchools":
                case "EducationMajors":
                    self.nowTemp[id][index].push(val);
                    break;
                case "Connections": //联系单独处理
                    self.nowTemp[id] = [{type:val,connections:[{id:self.app.fbConnectionObjectId, name:self.app.name}]}]//删除整个条件
                    break;
            }
            var updateObject = $('#'+id).find('li[index='+index+']');
            if(updateObject[0]){
                kit.addBorderGreen(updateObject)
            }

        }


        /**
         * 保存用户定位模板
         * @param t
         */
        this.addUseraudienceTemplate = function(t){

            //缓存吃中的数据，如果是新建，应该大部分为空
            self.cache.userAudienceTemplate.userAudienceTemplates.push(t)
            self.sessionData.cache = JSON.stringify(self.cache);

            var saved = JSON.parse(t.templateTargetingSpecs);
            self.temp = saved;//当前模板是哪个t
            self.tempIndex =t.id;
            self.sessionData.tempIndex = t.id;//存选中的模板
            self.nowTemp = saved;
            self.sessionData.temp = JSON.stringify(self.temp);//存选中的模板
            self.userTemp.userAudienceTemplates.push(t);

            ///下面是保存模板重点
            var xxx  = JSON.parse(self.sessionData.userTemp);
            xxx.userAudienceTemplates.push(t);
            self.sessionData.userTemp = JSON.stringify(xxx);

            self.sessionData.temp = JSON.stringify(self.nowTemp);
        }

        this.body = function(arr){
            var body = {param:{}};
            if(arr && (arr instanceof Array)){//[{key:"",value:""},{key:"",value:""}]
                for(var i=0;i<arr.length;i++){
                    var the = arr[i];
                    body.param[the.key] = the.value;
                }
            }else{//{key:"",value:""}
                body.param[arr.key] = arr.value;
            }
            body.param = JSON.stringify(body.param);
            return body;
        };
        this.other=[{text:I18N.getText('createAd', 'otherAudienceConditions'),class:"otherAudience"},
                    {text:I18N.getText('createAd', 'behavior'),class:"Behavior"},
                    {text:I18N.getText('createAd', 'languages'),class:"Languages"},
                    {text:I18N.getText('createAd', 'relationshipStatus'),sub:[{text:I18N.getText('createAd', 'sexuality'),class:"NewInterestedIn"},
                    {text:I18N.getText('createAd', 'relationshipStatus'),class:"NewRelationshipStatus"}],class:"relation"},
                    {text:I18N.getText('createAd', 'education'),sub:[{"text":I18N.getText('createAd', 'educationLevel'),class:"EducationStatuses"},
                    {"text":I18N.getText('createAd', 'researchAreas'),class:"EducationMajors"},
                    {"text":I18N.getText('createAd', 'college'),class:"EducationSchools"},
                    {"text":I18N.getText('createAd', 'universityYear'),class:"CollegeYears"}],class:"education"},
                    {"text":I18N.getText('createAd', 'work'),"sub":[{"text":I18N.getText('createAd', 'employer'),class:"WorkEmployers"},
                    {"text":I18N.getText('createAd', 'position'),class:"WorkPositions"},
                    {"text":I18N.getText('createAd', 'industry'),class:"Industries"}],class:"work"},
                    {text:I18N.getText('createAd', 'ethnic'),class:"EthnicAffinity"},
                    {text:I18N.getText('createAd', 'generations'),class:"Generation"},
                    {text:I18N.getText('createAd', 'parent'),"sub":[{"text":I18N.getText('createAd', 'parent') + I18N.getText('createAd', 'allInclude'),class:"FamilyStatuses"}],class:"parent"},
                    {"text":I18N.getText('createAd', 'politics'),class:"Politics"},
                    {"text":I18N.getText('createAd', 'lifeEvents'),class:"LifeEvents"}
        ];
        //this.other.isNewAudience = false;

        this.newints = [{"id":"1","text":I18N.getText('createAd', 'male'),"name":I18N.getText('createAd', 'male')},{"id":"2","text":I18N.getText('createAd', 'female'),"name":I18N.getText('createAd', 'female')},{"id":"3","text":I18N.getText('createAd', 'maleAndFemale'),"name":I18N.getText('createAd', 'maleAndFemale')}];

        this.relation = [{id:"1",text:I18N.getText('createAd', 'single'),name:I18N.getText('createAd', 'single')},{id:"2",text:I18N.getText('createAd', 'inaRelationship'),name:I18N.getText('createAd', 'inaRelationship')},{id:"3",text:I18N.getText('createAd', 'married'),name:I18N.getText('createAd', 'married')},{id:"4",text:I18N.getText('createAd', 'engaged'),name:I18N.getText('createAd', 'engaged')},
           {id:"6",text:I18N.getText('createAd', 'inaCivilUnion'),name:I18N.getText('createAd', 'inaCivilUnion')},{id:"7",text:I18N.getText('createAd', 'inaDomesticPartnership'),name:I18N.getText('createAd', 'inaDomesticPartnership')},{id:"8",text:I18N.getText('createAd', 'inaOpenRelationship'),name:I18N.getText('createAd', 'inaOpenRelationship')},
            {id:"9",text:I18N.getText('createAd', 'complicated'),name:I18N.getText('createAd', 'complicated')},{id:"10",text:I18N.getText('createAd', 'separated'),name:I18N.getText('createAd', 'separated')}, {id:"11",text:I18N.getText('createAd', 'divorced'),name:I18N.getText('createAd', 'divorced')},{id:"12",text:I18N.getText('createAd', 'widowed'),name:I18N.getText('createAd', 'widowed')}];


//        this.eth = [{id:"6009609045383",text:"西班牙族裔人群(美国 - 主要语言为英语)"},{id:"6009609033583",text:"西班牙族裔人群（美国 - 主要语言为西班牙语)"},{id:"3",text:"非洲裔美国人（美国)"},{id:"4",text:"西班牙族裔人群（美国 - 双语）"},{id:"5",text:"Asian American (US)" }, {id:"6",text:"西班牙族裔人群（美国 - 所有)"}];


        this.school = [{id:"1",text:I18N.getText('createAd', 'inHighSchool'),name:I18N.getText('createAd', 'inHighSchool')},{id:"2",text:I18N.getText('createAd', 'inCollege'),name:I18N.getText('createAd', 'inCollege')},{id:"3",text:I18N.getText('createAd', 'graduatedFromCollege'),name:I18N.getText('createAd', 'graduatedFromCollege')},{id:"4",text:I18N.getText('createAd', 'graduatedFromHighSchool'),name:I18N.getText('createAd', 'graduatedFromHighSchool')},{id:"5",text:I18N.getText('createAd', 'university'),name:I18N.getText('createAd', 'university')},{id:"6",text:I18N.getText('createAd', 'associateDegree'),name:I18N.getText('createAd', 'associateDegree')},{id:"7",text:I18N.getText('createAd', 'studyingMaster'),name:I18N.getText('createAd', 'studyingMaster')},{id:"8",text:I18N.getText('createAd', 'aGraduateSchool'),name:I18N.getText('createAd', 'aGraduateSchool')},{id:"9",text:I18N.getText('createAd', 'masterDegree'),name:I18N.getText('createAd', 'masterDegree')},{id:"10",text:I18N.getText('createAd', 'designedMasterDegree'),name:I18N.getText('createAd', 'designedMasterDegree')},{id:"11",text:I18N.getText('createAd', 'doctor'),name:I18N.getText('createAd', 'doctor')},{id:"12",text:I18N.getText('createAd', 'unspecified'),name:I18N.getText('createAd', 'unspecified')}, {id:"13",text:I18N.getText('createAd', 'aSecondarySchool'),name:I18N.getText('createAd', 'aSecondarySchool')}];
        //工作--行业 族裔 世代 父母–父母（统统包括） 政治（美国） 生活纪事
        if(this.sessionData.others && (this.sessionData.others!=undefined) && (this.sessionData.others!="undefined")){
           this.others = JSON.parse(this.sessionData.others);
        }else{
            http.do("/search/searchAdTargetingCategory",
                    {param:JSON.stringify({"locale":I18N.language})}).then(function(result){
                if(typeof(result)=="string") result = JSON.parse(result);
                self.others = result.data;
                self.sessionData.others = JSON.stringify(self.others);
            },function(err){});
        }
        //行为数据
        if(this.sessionData.behav&&this.sessionData.behav!="undefined"){
            this.behav = JSON.parse(this.sessionData.behav);
        }else{
            http.do("/search/searchBehaviors",
                    {param:JSON.stringify({
                           "type":"adTargetingCategory",
                           "classT":"behaviors",
                           "locale":I18N.language
                        })}).then(function(result){
                if(typeof(result)=="string") result = JSON.parse(result);
                self.behav = result.data;
                self.sessionData.behav = JSON.stringify(self.behav);
            },function(err){});
        }

        //兴趣 手型下拉菜单
        if(this.sessionData.intHand&&this.sessionData.intHand!="undefined"){
            this.intHand = JSON.parse(this.sessionData.intHand);
        }else{
            this.intHand = [];
        }

        //校验兴趣次是否失效
        this.filterValidInterest = function(Interests,fun){
            http.doAsync("/search/adInterestValid",{param : JSON.stringify(Interests)}).then(function(result){
                if(typeof(result)=="string") result = JSON.parse(result);
                fun(undefined,result.data);
            },function(err){
                fun(err);
            });
        };

        //所有有权限投放的app
        if (this.sessionData.resourApps && this.sessionData.resourApps != "undefined") {
            this.resourApps = JSON.parse(this.sessionData.resourApps);
        } else {
            http.doAsync("/connectionobjects/searchConnectionObjectsByResourceManage", {param: JSON.stringify({typeId: 2})})
                .then(function (result) {
                    if (typeof(result) == "string") result = JSON.parse(result);
                    var resourApps = $.map(result.data,function(v){
                         v.text = v.name;
                        return v;
                    });
                    self.resourApps = resourApps;
                    self.sessionData.resourApps = JSON.stringify(resourApps);
                }, function (err) {

                });
        }

        this.bidInfo = {
            "outlink" : {
                defaultOptimizationGoal : "LINK_CLICKS",
                defaultBillingEvent : "LINK_CLICKS",
                optimizationGoalList : [
                    {id : "LINK_CLICKS", text : I18N.getText('createAd', 'websiteLinkClicks'), value : 1,
                        billingEvents : [{id : "LINK_CLICKS", text : I18N.getText('createAd', 'linkClicks'), value : 0},{id : "IMPRESSIONS" , text : I18N.getText('createAd', 'impressions'), value : 1}]},
                    {id : "IMPRESSIONS", text : I18N.getText('createAd', 'impressions'), value : 2,
                        billingEvents : [{id : "IMPRESSIONS" , text : I18N.getText('createAd', 'impressions'), value : 0}]},
                    {id : "REACH", text : I18N.getText('createAd', 'dailyUniqueReach'), value : 3,
                        billingEvents : [{id : "IMPRESSIONS" , text : I18N.getText('createAd', 'impressions'), value : 0}]}
                ]
            },
            "app" : {
                defaultOptimizationGoal : "APP_INSTALLS",
                defaultBillingEvent : "IMPRESSIONS",
                optimizationGoalList : [
                    {id : "APP_INSTALLS", text : I18N.getText('createAd', 'appInstalls'), value : 0,
                        billingEvents :[{id : "IMPRESSIONS", text : I18N.getText('createAd', 'impressions'), value:0},{id : "APP_INSTALLS", text : I18N.getText('createAd', 'appInstalls'), value:1}]},
                    {id : "LINK_CLICKS", text : I18N.getText('createAd', 'linkClicks'), value : 1,
                        billingEvents : [{id : "LINK_CLICKS", text : I18N.getText('createAd', 'linkClicks'), value : 0},{id : "IMPRESSIONS" , text : I18N.getText('createAd', 'impressions'), value : 1}]
                    }
                ]
            }
        }

        /**
         * 只清除部分数据
         */
        this.clearSession=function() {
            delete window.sessionStorage.app;
            delete window.sessionStorage.userAudienceResults;
            delete window.sessionStorage.tempIndex;
            delete window.sessionStorage.prods;
            delete window.sessionStorage.prod;
            delete window.sessionStorage.apps;
            delete window.sessionStorage.resourApps;
            delete window.sessionStorage.Gender;
            delete window.sessionStorage.cache;
            delete window.sessionStorage.temp;
            delete window.sessionStorage.userTemp;
            delete window.sessionStorage.aca;
            delete window.sessionStorage.pageList;
            delete window.sessionStorage.adTitle;
            delete window.sessionStorage.page;
            delete window.sessionStorage.radio;
            delete window.sessionStorage.adTitleList;
            delete window.sessionStorage.actionOption;
            delete window.sessionStorage.entrustAccounts;
            delete window.sessionStorage.adCampSeq;
            delete window.sessionStorage.tagNames;
        };
        //返回空的出价参数模型
        this.getBidInfoVo=function(gIndex, locIndex){
            //todo o,undefined
            if (gIndex && locIndex) {
                gIndex=parseInt(gIndex);
                locIndex=parseInt(locIndex);
                var defaultOptimizationGoal;
                var defaultBillingEvent;
                if (self.app.productType  == 'outlink'){
                    //外链
                    defaultOptimizationGoal = self.bidInfo.outlink.defaultOptimizationGoal;
                    defaultBillingEvent = self.bidInfo.outlink.defaultBillingEvent;
                } else {
                    defaultOptimizationGoal = self.bidInfo.app.defaultOptimizationGoal;
                    defaultBillingEvent = self.bidInfo.app.defaultBillingEvent;
                }

                var info = {budget:0, optimizationGoal:defaultOptimizationGoal, billingEvent:defaultBillingEvent, sBidAmount:0,budgetType:0,isAutoBid:0,gindex:gIndex||0,loc_index:locIndex||0};

                if (self.prices[gIndex]&&self.prices[gIndex][locIndex]) {
                    info= self.prices[gIndex][locIndex];
                }else {
                    if (!self.prices[gIndex]) {
                        self.prices[gIndex]=[];
                    }
                    self.prices[gIndex][locIndex]=info;
                }

                return info;
            }else {
                return false;
            }
        }
    };
    return new Data();
});
